
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>xml.etree.ElementTree --- ElementTree XML API &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="xml.dom --- The Document Object Model API" href="xml.dom.html" />
    <link rel="prev" title="XML处理模块" href="xml.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/xml.etree.elementtree.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="xml.dom --- The Document Object Model API"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="xml.html" title="XML处理模块"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">结构化标记处理工具</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.etree.ElementTree">
<span id="xml-etree-elementtree-the-elementtree-xml-api"></span><h1><a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> ---  ElementTree XML API<a class="headerlink" href="#module-xml.etree.ElementTree" title="永久链接至标题">¶</a></h1>
<p><strong>源代码：</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/xml/etree/ElementTree.py">Lib/xml/etree/ElementTree.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> 模块实现了一个简单高效的API，用于解析和创建XML数据。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>只要有可能，这个模块将使用快速实现。<code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.cElementTree</span></code> 模块已弃用。</p>
</div>
<div class="admonition warning">
<p class="admonition-title">警告</p>
<p><a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> 模块对于恶意构建的数据是不安全的。如果需要解析不可信或未经身份验证的数据，请参见 <a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML 漏洞</span></a> 。</p>
</div>
<div class="section" id="tutorial">
<h2>教程<a class="headerlink" href="#tutorial" title="永久链接至标题">¶</a></h2>
<p>这是一个使用 <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> （简称 <code class="docutils literal notranslate"><span class="pre">ET</span></code> ）的简短教程。目标是演示模块的一些构建块和基本概念。</p>
<div class="section" id="xml-tree-and-elements">
<h3>XML树和元素<a class="headerlink" href="#xml-tree-and-elements" title="永久链接至标题">¶</a></h3>
<p>XML是一种固有的分层数据格式，最自然的表示方法是使用树。为此， <code class="docutils literal notranslate"><span class="pre">ET</span></code> 有两个类 <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> 将整个XML文档表示为一个树， <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> 表示该树中的单个节点。与整个文档的交互（读写文件）通常在 <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> 级别完成。与单个XML元素及其子元素的交互是在 <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> 级别完成的。</p>
</div>
<div class="section" id="parsing-xml">
<span id="elementtree-parsing-xml"></span><h3>解析XML<a class="headerlink" href="#parsing-xml" title="永久链接至标题">¶</a></h3>
<p>我们将使用以下XML文档作为本节的示例数据：</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>1<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>4<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Panama&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>68<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>13600<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Costa Rica&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Colombia&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
<p>我们可以通过从文件中读取来导入此数据：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">as</span> <span class="nn">ET</span>
<span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s1">&#39;country_data.xml&#39;</span><span class="p">)</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">getroot</span><span class="p">()</span>
</pre></div>
</div>
<p>或直接从字符串中：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">root</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="n">country_data_as_string</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#xml.etree.ElementTree.fromstring" title="xml.etree.ElementTree.fromstring"><code class="xref py py-func docutils literal notranslate"><span class="pre">fromstring()</span></code></a> 将XML从字符串直接解析为 <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> ，该元素是已解析树的根元素。其他解析函数可能会创建一个 <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> 。确切的信息请检查文档。</p>
<p>作为一个 <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> ， <code class="docutils literal notranslate"><span class="pre">root</span></code> 有一个标记和一个属性字典:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="o">.</span><span class="n">tag</span>
<span class="go">&#39;data&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="o">.</span><span class="n">attrib</span>
<span class="go">{}</span>
</pre></div>
</div>
<p>它还有我们可以迭代的子节点：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">child</span> <span class="ow">in</span> <span class="n">root</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">child</span><span class="o">.</span><span class="n">tag</span><span class="p">,</span> <span class="n">child</span><span class="o">.</span><span class="n">attrib</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">country {&#39;name&#39;: &#39;Liechtenstein&#39;}</span>
<span class="go">country {&#39;name&#39;: &#39;Singapore&#39;}</span>
<span class="go">country {&#39;name&#39;: &#39;Panama&#39;}</span>
</pre></div>
</div>
<p>子级是可以嵌套的，我们可以通过索引访问特定的子级节点：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">text</span>
<span class="go">&#39;2008&#39;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>并非XML输入的所有元素都将作为解析树的元素结束。目前，此模块跳过输入中的任何XML注释、处理指令和文档类型声明。然而，使用这个模块的API而不是从XML文本解析构建的树可以包含注释和处理指令，生成XML输出时同样包含这些注释和处理指令。可以通过将自定义 <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> 实例传递给 <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> 构造函数来访问文档类型声明。</p>
</div>
</div>
<div class="section" id="pull-api-for-non-blocking-parsing">
<span id="elementtree-pull-parsing"></span><h3>Pull API进行非阻塞解析<a class="headerlink" href="#pull-api-for-non-blocking-parsing" title="永久链接至标题">¶</a></h3>
<p>Most parsing functions provided by this module require the whole document
to be read at once before returning any result.  It is possible to use an
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> and feed data into it incrementally, but it is a push API that
calls methods on a callback target, which is too low-level and inconvenient for
most needs.  Sometimes what the user really wants is to be able to parse XML
incrementally, without blocking operations, while enjoying the convenience of
fully constructed <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> objects.</p>
<p>The most powerful tool for doing this is <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLPullParser</span></code></a>.  It does not
require a blocking read to obtain the XML data, and is instead fed with data
incrementally with <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.feed" title="xml.etree.ElementTree.XMLPullParser.feed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLPullParser.feed()</span></code></a> calls.  To get the parsed XML
elements, call <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLPullParser.read_events()</span></code></a>.  Here is an example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XMLPullParser</span><span class="p">([</span><span class="s1">&#39;start&#39;</span><span class="p">,</span> <span class="s1">&#39;end&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;mytag&gt;sometext&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">read_events</span><span class="p">())</span>
<span class="go">[(&#39;start&#39;, &lt;Element &#39;mytag&#39; at 0x7fa66db2be58&gt;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39; more text&lt;/mytag&gt;&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">event</span><span class="p">,</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">parser</span><span class="o">.</span><span class="n">read_events</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">event</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">elem</span><span class="o">.</span><span class="n">tag</span><span class="p">,</span> <span class="s1">&#39;text=&#39;</span><span class="p">,</span> <span class="n">elem</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">end</span>
</pre></div>
</div>
<p>The obvious use case is applications that operate in a non-blocking fashion
where the XML data is being received from a socket or read incrementally from
some storage device.  In such cases, blocking reads are unacceptable.</p>
<p>Because it's so flexible, <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLPullParser</span></code></a> can be inconvenient to use for
simpler use-cases.  If you don't mind your application blocking on reading XML
data but would still like to have incremental parsing capabilities, take a look
at <a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code class="xref py py-func docutils literal notranslate"><span class="pre">iterparse()</span></code></a>.  It can be useful when you're reading a large XML document
and don't want to hold it wholly in memory.</p>
</div>
<div class="section" id="finding-interesting-elements">
<h3>寻找有趣的元素<a class="headerlink" href="#finding-interesting-elements" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> 有一些很有效的方法，可帮助递归遍历其下的所有子树（包括子级，子级的子级，等等）。例如 <a class="reference internal" href="#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.iter()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">neighbor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s1">&#39;neighbor&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">neighbor</span><span class="o">.</span><span class="n">attrib</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">{&#39;name&#39;: &#39;Austria&#39;, &#39;direction&#39;: &#39;E&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Switzerland&#39;, &#39;direction&#39;: &#39;W&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Malaysia&#39;, &#39;direction&#39;: &#39;N&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Costa Rica&#39;, &#39;direction&#39;: &#39;W&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Colombia&#39;, &#39;direction&#39;: &#39;E&#39;}</span>
</pre></div>
</div>
<p><a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findall()</span></code></a> 仅查找当前元素的直接子元素中带有指定标签的元素。 <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.find()</span></code></a> 找带有特定标签的 <em>第一个</em> 子级，然后可以用 <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Element.text</span></code></a> 访问元素的文本内容。 <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Element.text</span></code></a> 访问元素的属性:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">country</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;country&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">rank</span> <span class="o">=</span> <span class="n">country</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">text</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">country</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">rank</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Liechtenstein 1</span>
<span class="go">Singapore 4</span>
<span class="go">Panama 68</span>
</pre></div>
</div>
<p>通过使用 <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">XPath</span></a> ，可以更精确地指定要查找的元素。</p>
</div>
<div class="section" id="modifying-an-xml-file">
<h3>修改XML文件<a class="headerlink" href="#modifying-an-xml-file" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> 提供了一种构建XML文档并将其写入文件的简单方法。  <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code></a> 方法可达到此目的。</p>
<p>创建后可以直接操作 <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> 对象。例如：使用 <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Element.text</span></code></a> 修改文本字段，使用 <a class="reference internal" href="#xml.etree.ElementTree.Element.set" title="xml.etree.ElementTree.Element.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.set()</span></code></a> 方法添加和修改属性，以及使用  <a class="reference internal" href="#xml.etree.ElementTree.Element.append" title="xml.etree.ElementTree.Element.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.append()</span></code></a> 添加新的子元素。</p>
<p>假设我们要在每个国家/地区的中添加一个排名，并在rank元素中添加一个 <code class="docutils literal notranslate"><span class="pre">updated</span></code> 属性：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">rank</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">new_rank</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">rank</span><span class="o">.</span><span class="n">text</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="n">rank</span><span class="o">.</span><span class="n">text</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">new_rank</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">rank</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;updated&#39;</span><span class="p">,</span> <span class="s1">&#39;yes&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>生成的XML现在看起来像这样：</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>2<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>5<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Panama&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>69<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>13600<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Costa Rica&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Colombia&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
<p>可以使用 <a class="reference internal" href="#xml.etree.ElementTree.Element.remove" title="xml.etree.ElementTree.Element.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.remove()</span></code></a> 删除元素。假设我们要删除排名高于50的所有国家/地区:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">country</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;country&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">rank</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">country</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">rank</span> <span class="o">&gt;</span> <span class="mi">50</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">root</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">country</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>生成的XML现在看起来像这样：</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>2<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>5<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="building-xml-documents">
<h3>构建XML文档<a class="headerlink" href="#building-xml-documents" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code class="xref py py-func docutils literal notranslate"><span class="pre">SubElement()</span></code></a> 函数还提供了一种便捷方法来为给定元素创建新的子元素:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">Element</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ET</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="parsing-xml-with-namespaces">
<h3>使用命名空间解析XML<a class="headerlink" href="#parsing-xml-with-namespaces" title="永久链接至标题">¶</a></h3>
<p>If the XML input has <a class="reference external" href="https://en.wikipedia.org/wiki/XML_namespace">namespaces</a>, tags and attributes
with prefixes in the form <code class="docutils literal notranslate"><span class="pre">prefix:sometag</span></code> get expanded to
<code class="docutils literal notranslate"><span class="pre">{uri}sometag</span></code> where the <em>prefix</em> is replaced by the full <em>URI</em>.
Also, if there is a <a class="reference external" href="https://www.w3.org/TR/xml-names/#defaulting">default namespace</a>,
that full URI gets prepended to all of the non-prefixed tags.</p>
<p>Here is an XML example that incorporates two namespaces, one with the
prefix &quot;fictional&quot; and the other serving as the default namespace:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;actors</span> <span class="na">xmlns:fictional=</span><span class="s">&quot;http://characters.example.com&quot;</span>
        <span class="na">xmlns=</span><span class="s">&quot;http://people.example.com&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;actor&gt;</span>
        <span class="nt">&lt;name&gt;</span>John Cleese<span class="nt">&lt;/name&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Lancelot<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Archie Leach<span class="nt">&lt;/fictional:character&gt;</span>
    <span class="nt">&lt;/actor&gt;</span>
    <span class="nt">&lt;actor&gt;</span>
        <span class="nt">&lt;name&gt;</span>Eric Idle<span class="nt">&lt;/name&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Sir Robin<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Gunther<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Commander Clement<span class="nt">&lt;/fictional:character&gt;</span>
    <span class="nt">&lt;/actor&gt;</span>
<span class="nt">&lt;/actors&gt;</span>
</pre></div>
</div>
<p>One way to search and explore this XML example is to manually add the
URI to every tag or attribute in the xpath of a
<a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> or <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">root</span> <span class="o">=</span> <span class="n">fromstring</span><span class="p">(</span><span class="n">xml_text</span><span class="p">)</span>
<span class="k">for</span> <span class="n">actor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;{http://people.example.com}actor&#39;</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">actor</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;{http://people.example.com}name&#39;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">actor</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;{http://characters.example.com}character&#39;</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39; |--&gt;&#39;</span><span class="p">,</span> <span class="n">char</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
</pre></div>
</div>
<p>A better way to search the namespaced XML example is to create a
dictionary with your own prefixes and use those in the search functions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">ns</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;real_person&#39;</span><span class="p">:</span> <span class="s1">&#39;http://people.example.com&#39;</span><span class="p">,</span>
      <span class="s1">&#39;role&#39;</span><span class="p">:</span> <span class="s1">&#39;http://characters.example.com&#39;</span><span class="p">}</span>

<span class="k">for</span> <span class="n">actor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;real_person:actor&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">actor</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;real_person:name&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">name</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">actor</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;role:character&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s1">&#39; |--&gt;&#39;</span><span class="p">,</span> <span class="n">char</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
</pre></div>
</div>
<p>These two approaches both output:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">John</span> <span class="n">Cleese</span>
 <span class="o">|--&gt;</span> <span class="n">Lancelot</span>
 <span class="o">|--&gt;</span> <span class="n">Archie</span> <span class="n">Leach</span>
<span class="n">Eric</span> <span class="n">Idle</span>
 <span class="o">|--&gt;</span> <span class="n">Sir</span> <span class="n">Robin</span>
 <span class="o">|--&gt;</span> <span class="n">Gunther</span>
 <span class="o">|--&gt;</span> <span class="n">Commander</span> <span class="n">Clement</span>
</pre></div>
</div>
</div>
<div class="section" id="additional-resources">
<h3>其他资源<a class="headerlink" href="#additional-resources" title="永久链接至标题">¶</a></h3>
<p>See <a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a> for tutorials and links to other
docs.</p>
</div>
</div>
<div class="section" id="xpath-support">
<span id="elementtree-xpath"></span><h2>XPath支持<a class="headerlink" href="#xpath-support" title="永久链接至标题">¶</a></h2>
<p>This module provides limited support for
<a class="reference external" href="https://www.w3.org/TR/xpath">XPath expressions</a> for locating elements in a
tree.  The goal is to support a small subset of the abbreviated syntax; a full
XPath engine is outside the scope of the module.</p>
<div class="section" id="example">
<h3>示例<a class="headerlink" href="#example" title="永久链接至标题">¶</a></h3>
<p>Here's an example that demonstrates some of the XPath capabilities of the
module.  We'll be using the <code class="docutils literal notranslate"><span class="pre">countrydata</span></code> XML document from the
<a class="reference internal" href="#elementtree-parsing-xml"><span class="std std-ref">Parsing XML</span></a> section:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">as</span> <span class="nn">ET</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="n">countrydata</span><span class="p">)</span>

<span class="c1"># Top-level elements</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.&quot;</span><span class="p">)</span>

<span class="c1"># All &#39;neighbor&#39; grand-children of &#39;country&#39; children of the top-level</span>
<span class="c1"># elements</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;./country/neighbor&quot;</span><span class="p">)</span>

<span class="c1"># Nodes with name=&#39;Singapore&#39; that have a &#39;year&#39; child</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//year/..[@name=&#39;Singapore&#39;]&quot;</span><span class="p">)</span>

<span class="c1"># &#39;year&#39; nodes that are children of nodes with name=&#39;Singapore&#39;</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//*[@name=&#39;Singapore&#39;]/year&quot;</span><span class="p">)</span>

<span class="c1"># All &#39;neighbor&#39; nodes that are the second child of their parent</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//neighbor[2]&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="supported-xpath-syntax">
<h3>支持的XPath语法<a class="headerlink" href="#supported-xpath-syntax" title="永久链接至标题">¶</a></h3>
<table class="docutils align-default">
<colgroup>
<col style="width: 30%" />
<col style="width: 70%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>语法</p></th>
<th class="head"><p>含义</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">tag</span></code></p></td>
<td><p>Selects all child elements with the given tag.
For example, <code class="docutils literal notranslate"><span class="pre">spam</span></code> selects all child elements
named <code class="docutils literal notranslate"><span class="pre">spam</span></code>, and <code class="docutils literal notranslate"><span class="pre">spam/egg</span></code> selects all
grandchildren named <code class="docutils literal notranslate"><span class="pre">egg</span></code> in all children named
<code class="docutils literal notranslate"><span class="pre">spam</span></code>.</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">*</span></code></p></td>
<td><p>Selects all child elements.  For example, <code class="docutils literal notranslate"><span class="pre">*/egg</span></code>
selects all grandchildren named <code class="docutils literal notranslate"><span class="pre">egg</span></code>.</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">.</span></code></p></td>
<td><p>选择当前节点。这在路径的开头非常有用，用于指示它是相对路径。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">//</span></code></p></td>
<td><p>Selects all subelements, on all levels beneath the
current  element.  For example, <code class="docutils literal notranslate"><span class="pre">.//egg</span></code> selects
all <code class="docutils literal notranslate"><span class="pre">egg</span></code> elements in the entire tree.</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">..</span></code></p></td>
<td><p>Selects the parent element.  Returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if the
path attempts to reach the ancestors of the start
element (the element <code class="docutils literal notranslate"><span class="pre">find</span></code> was called on).</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">[&#64;attrib]</span></code></p></td>
<td><p>选择具有给定属性的所有元素。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">[&#64;attrib='value']</span></code></p></td>
<td><p>选择给定属性具有给定值的所有元素。该值不能包含引号。</p></td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">[tag]</span></code></p></td>
<td><p>选择所有包含 <code class="docutils literal notranslate"><span class="pre">tag</span></code> 子元素的元素。只支持直系子元素。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">[.='text']</span></code></p></td>
<td><p>选择完整文本内容等于 <code class="docutils literal notranslate"><span class="pre">text</span></code> 的所有元素（包括后代）。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</td>
</tr>
<tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">[tag='text']</span></code></p></td>
<td><p>选择所有包含名为 <code class="docutils literal notranslate"><span class="pre">tag</span></code> 的子元素的元素，这些子元素（包括后代）的完整文本内容等于给定的 <code class="docutils literal notranslate"><span class="pre">text</span></code> 。</p></td>
</tr>
<tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">[position]</span></code></p></td>
<td><p>Selects all elements that are located at the given
position.  The position can be either an integer
(1 is the first position), the expression <code class="docutils literal notranslate"><span class="pre">last()</span></code>
(for the last position), or a position relative to
the last position (e.g. <code class="docutils literal notranslate"><span class="pre">last()-1</span></code>).</p></td>
</tr>
</tbody>
</table>
<p>谓词（方括号内的表达式）之前必须带有标签名称，星号或其他谓词。<code class="docutils literal notranslate"><span class="pre">position</span></code> 谓词前必须有标签名称。</p>
</div>
</div>
<div class="section" id="reference">
<h2>参考<a class="headerlink" href="#reference" title="永久链接至标题">¶</a></h2>
<div class="section" id="functions">
<span id="elementtree-functions"></span><h3>函数<a class="headerlink" href="#functions" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="xml.etree.ElementTree.Comment">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">Comment</code><span class="sig-paren">(</span><em class="sig-param">text=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Comment" title="永久链接至目标">¶</a></dt>
<dd><p>Comment element factory.  This factory function creates a special element
that will be serialized as an XML comment by the standard serializer.  The
comment string can be either a bytestring or a Unicode string.  <em>text</em> is a
string containing the comment string.  Returns an element instance
representing a comment.</p>
<p>Note that <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> skips over comments in the input
instead of creating comment objects for them. An <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> will
only contain comment nodes if they have been inserted into to
the tree using one of the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> methods.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.dump">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">dump</code><span class="sig-paren">(</span><em class="sig-param">elem</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.dump" title="永久链接至目标">¶</a></dt>
<dd><p>Writes an element tree or element structure to sys.stdout.  This function
should be used for debugging only.</p>
<p>The exact output format is implementation dependent.  In this version, it's
written as an ordinary XML file.</p>
<p><em>elem</em> is an element tree or an individual element.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.fromstring">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">fromstring</code><span class="sig-paren">(</span><em class="sig-param">text</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.fromstring" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML section from a string constant.  Same as <a class="reference internal" href="#xml.etree.ElementTree.XML" title="xml.etree.ElementTree.XML"><code class="xref py py-func docutils literal notranslate"><span class="pre">XML()</span></code></a>.  <em>text</em>
is a string containing XML data.  <em>parser</em> is an optional parser instance.
If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.
Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.fromstringlist">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">fromstringlist</code><span class="sig-paren">(</span><em class="sig-param">sequence</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.fromstringlist" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML document from a sequence of string fragments.  <em>sequence</em> is a
list or other sequence containing XML data fragments.  <em>parser</em> is an
optional parser instance.  If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a>
parser is used.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.iselement">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">iselement</code><span class="sig-paren">(</span><em class="sig-param">element</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.iselement" title="永久链接至目标">¶</a></dt>
<dd><p>Check if an object appears to be a valid element object.  <em>element</em> is an
element instance.  Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if this is an element object.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.iterparse">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">iterparse</code><span class="sig-paren">(</span><em class="sig-param">source</em>, <em class="sig-param">events=None</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.iterparse" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML section into an element tree incrementally, and reports what's
going on to the user.  <em>source</em> is a filename or <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>
containing XML data.  <em>events</em> is a sequence of events to report back.  The
supported events are the strings <code class="docutils literal notranslate"><span class="pre">&quot;start&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;end&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;start-ns&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&quot;end-ns&quot;</span></code> (the &quot;ns&quot; events are used to get detailed namespace
information).  If <em>events</em> is omitted, only <code class="docutils literal notranslate"><span class="pre">&quot;end&quot;</span></code> events are reported.
<em>parser</em> is an optional parser instance.  If not given, the standard
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  <em>parser</em> must be a subclass of
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> and can only use the default <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> as a
target.  Returns an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> providing <code class="docutils literal notranslate"><span class="pre">(event,</span> <span class="pre">elem)</span></code> pairs.</p>
<p>Note that while <a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code class="xref py py-func docutils literal notranslate"><span class="pre">iterparse()</span></code></a> builds the tree incrementally, it issues
blocking reads on <em>source</em> (or the file it names).  As such, it's unsuitable
for applications where blocking reads can't be made.  For fully non-blocking
parsing, see <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLPullParser</span></code></a>.</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p><a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code class="xref py py-func docutils literal notranslate"><span class="pre">iterparse()</span></code></a> only guarantees that it has seen the &quot;&gt;&quot; character of a
starting tag when it emits a &quot;start&quot; event, so the attributes are defined,
but the contents of the text and tail attributes are undefined at that
point.  The same applies to the element children; they may or may not be
present.</p>
<p>If you need a fully populated element, look for &quot;end&quot; events instead.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified deprecated">3.4 版后已移除: </span><em>parser</em> 参数。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.parse">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">parse</code><span class="sig-paren">(</span><em class="sig-param">source</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.parse" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML section into an element tree.  <em>source</em> is a filename or file
object containing XML data.  <em>parser</em> is an optional parser instance.  If
not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns an
<a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.ProcessingInstruction">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">ProcessingInstruction</code><span class="sig-paren">(</span><em class="sig-param">target</em>, <em class="sig-param">text=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ProcessingInstruction" title="永久链接至目标">¶</a></dt>
<dd><p>PI element factory.  This factory function creates a special element that
will be serialized as an XML processing instruction.  <em>target</em> is a string
containing the PI target.  <em>text</em> is a string containing the PI contents, if
given.  Returns an element instance, representing a processing instruction.</p>
<p>Note that <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> skips over processing instructions
in the input instead of creating comment objects for them. An
<a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> will only contain processing instruction nodes if
they have been inserted into to the tree using one of the
<a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> methods.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.register_namespace">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">register_namespace</code><span class="sig-paren">(</span><em class="sig-param">prefix</em>, <em class="sig-param">uri</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.register_namespace" title="永久链接至目标">¶</a></dt>
<dd><p>Registers a namespace prefix.  The registry is global, and any existing
mapping for either the given prefix or the namespace URI will be removed.
<em>prefix</em> is a namespace prefix.  <em>uri</em> is a namespace uri.  Tags and
attributes in this namespace will be serialized with the given prefix, if at
all possible.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.SubElement">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">SubElement</code><span class="sig-paren">(</span><em class="sig-param">parent</em>, <em class="sig-param">tag</em>, <em class="sig-param">attrib={}</em>, <em class="sig-param">**extra</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.SubElement" title="永久链接至目标">¶</a></dt>
<dd><p>Subelement factory.  This function creates an element instance, and appends
it to an existing element.</p>
<p>The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings.  <em>parent</em> is the parent element.  <em>tag</em> is
the subelement name.  <em>attrib</em> is an optional dictionary, containing element
attributes.  <em>extra</em> contains additional attributes, given as keyword
arguments.  Returns an element instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.tostring">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">tostring</code><span class="sig-paren">(</span><em class="sig-param">element</em>, <em class="sig-param">encoding=&quot;us-ascii&quot;</em>, <em class="sig-param">method=&quot;xml&quot;</em>, <em class="sig-param">*</em>, <em class="sig-param">short_empty_elements=True</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.tostring" title="永久链接至目标">¶</a></dt>
<dd><p>Generates a string representation of an XML element, including all
subelements.  <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.  <em>encoding</em> <a class="footnote-reference brackets" href="#id8" id="id1">1</a> is
the output encoding (default is US-ASCII).  Use <code class="docutils literal notranslate"><span class="pre">encoding=&quot;unicode&quot;</span></code> to
generate a Unicode string (otherwise, a bytestring is generated).  <em>method</em>
is either <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).
<em>short_empty_elements</em> has the same meaning as in <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code></a>.
Returns an (optionally) encoded string containing the XML data.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能: </span><em>short_empty_elements</em> 形参。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.tostringlist">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">tostringlist</code><span class="sig-paren">(</span><em class="sig-param">element</em>, <em class="sig-param">encoding=&quot;us-ascii&quot;</em>, <em class="sig-param">method=&quot;xml&quot;</em>, <em class="sig-param">*</em>, <em class="sig-param">short_empty_elements=True</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.tostringlist" title="永久链接至目标">¶</a></dt>
<dd><p>Generates a string representation of an XML element, including all
subelements.  <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.  <em>encoding</em> <a class="footnote-reference brackets" href="#id8" id="id2">1</a> is
the output encoding (default is US-ASCII).  Use <code class="docutils literal notranslate"><span class="pre">encoding=&quot;unicode&quot;</span></code> to
generate a Unicode string (otherwise, a bytestring is generated).  <em>method</em>
is either <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).
<em>short_empty_elements</em> has the same meaning as in <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code></a>.
Returns a list of (optionally) encoded strings containing the XML data.
It does not guarantee any specific sequence, except that
<code class="docutils literal notranslate"><span class="pre">b&quot;&quot;.join(tostringlist(element))</span> <span class="pre">==</span> <span class="pre">tostring(element)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能: </span><em>short_empty_elements</em> 形参。</p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.XML">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">XML</code><span class="sig-paren">(</span><em class="sig-param">text</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XML" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML section from a string constant.  This function can be used to
embed &quot;XML literals&quot; in Python code.  <em>text</em> is a string containing XML
data.  <em>parser</em> is an optional parser instance.  If not given, the standard
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.XMLID">
<code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">XMLID</code><span class="sig-paren">(</span><em class="sig-param">text</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLID" title="永久链接至目标">¶</a></dt>
<dd><p>Parses an XML section from a string constant, and also returns a dictionary
which maps from element id:s to elements.  <em>text</em> is a string containing XML
data.  <em>parser</em> is an optional parser instance.  If not given, the standard
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns a tuple containing an
<a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance and a dictionary.</p>
</dd></dl>

</div>
</div>
<div class="section" id="xinclude-support">
<span id="elementtree-xinclude"></span><h2>XInclude 支持<a class="headerlink" href="#xinclude-support" title="永久链接至标题">¶</a></h2>
<p>This module provides limited support for
<a class="reference external" href="https://www.w3.org/TR/xinclude/">XInclude directives</a>, via the <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementInclude</span></code> helper module.  This module can be used to insert subtrees and text strings into element trees, based on information in the tree.</p>
<div class="section" id="id3">
<h3>示例<a class="headerlink" href="#id3" title="永久链接至标题">¶</a></h3>
<p>Here's an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the <code class="docutils literal notranslate"><span class="pre">{http://www.w3.org/2001/XInclude}include</span></code> element and set the <strong>parse</strong> attribute to <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, and use the <strong>href</strong> attribute to specify the document to include.</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;document</span> <span class="na">xmlns:xi=</span><span class="s">&quot;http://www.w3.org/2001/XInclude&quot;</span><span class="nt">&gt;</span>
  <span class="nt">&lt;xi:include</span> <span class="na">href=</span><span class="s">&quot;source.xml&quot;</span> <span class="na">parse=</span><span class="s">&quot;xml&quot;</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/document&gt;</span>
</pre></div>
</div>
<p>By default, the <strong>href</strong> attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.</p>
<p>To process this file, load it as usual, and pass the root element to the <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> module:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.etree</span> <span class="kn">import</span> <span class="n">ElementTree</span><span class="p">,</span> <span class="n">ElementInclude</span>

<span class="n">tree</span> <span class="o">=</span> <span class="n">ElementTree</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;document.xml&quot;</span><span class="p">)</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">getroot</span><span class="p">()</span>

<span class="n">ElementInclude</span><span class="o">.</span><span class="n">include</span><span class="p">(</span><span class="n">root</span><span class="p">)</span>
</pre></div>
</div>
<p>The ElementInclude module replaces the <code class="docutils literal notranslate"><span class="pre">{http://www.w3.org/2001/XInclude}include</span></code> element with the root element from the <strong>source.xml</strong> document. The result might look something like this:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="nt">&lt;document</span> <span class="na">xmlns:xi=</span><span class="s">&quot;http://www.w3.org/2001/XInclude&quot;</span><span class="nt">&gt;</span>
  <span class="nt">&lt;para&gt;</span>This is a paragraph.<span class="nt">&lt;/para&gt;</span>
<span class="nt">&lt;/document&gt;</span>
</pre></div>
</div>
<p>If the <strong>parse</strong> attribute is omitted, it defaults to &quot;xml&quot;. The href attribute is required.</p>
<p>To include a text document, use the <code class="docutils literal notranslate"><span class="pre">{http://www.w3.org/2001/XInclude}include</span></code> element, and set the <strong>parse</strong> attribute to &quot;text&quot;:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;document</span> <span class="na">xmlns:xi=</span><span class="s">&quot;http://www.w3.org/2001/XInclude&quot;</span><span class="nt">&gt;</span>
  Copyright (c) <span class="nt">&lt;xi:include</span> <span class="na">href=</span><span class="s">&quot;year.txt&quot;</span> <span class="na">parse=</span><span class="s">&quot;text&quot;</span> <span class="nt">/&gt;</span>.
<span class="nt">&lt;/document&gt;</span>
</pre></div>
</div>
<p>结果可能如下所示：</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="nt">&lt;document</span> <span class="na">xmlns:xi=</span><span class="s">&quot;http://www.w3.org/2001/XInclude&quot;</span><span class="nt">&gt;</span>
  Copyright (c) 2003.
<span class="nt">&lt;/document&gt;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="id4">
<h2>参考<a class="headerlink" href="#id4" title="永久链接至标题">¶</a></h2>
<div class="section" id="elementinclude-functions">
<span id="id5"></span><h3>函数<a class="headerlink" href="#elementinclude-functions" title="永久链接至标题">¶</a></h3>
<dl class="function">
<dt id="xml.etree.ElementTree.xml.etree.ElementInclude.default_loader">
<code class="sig-prename descclassname">xml.etree.ElementInclude.</code><code class="sig-name descname">default_loader</code><span class="sig-paren">(</span><em class="sig-param">href</em>, <em class="sig-param">parse</em>, <em class="sig-param">encoding=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.xml.etree.ElementInclude.default_loader" title="永久链接至目标">¶</a></dt>
<dd><p>Default loader. This default loader reads an included resource from disk.  <em>href</em> is a URL.
<em>parse</em> is for parse mode either &quot;xml&quot; or &quot;text&quot;.  <em>encoding</em>
is an optional text encoding.  If not given, encoding is <code class="docutils literal notranslate"><span class="pre">utf-8</span></code>.  Returns the
expanded resource.  If the parse mode is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, this is an ElementTree
instance.  If the parse mode is &quot;text&quot;, this is a Unicode string.  If the
loader fails, it can return None or raise an exception.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.xml.etree.ElementInclude.include">
<code class="sig-prename descclassname">xml.etree.ElementInclude.</code><code class="sig-name descname">include</code><span class="sig-paren">(</span><em class="sig-param">elem</em>, <em class="sig-param">loader=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.xml.etree.ElementInclude.include" title="永久链接至目标">¶</a></dt>
<dd><p>This function expands XInclude directives.  <em>elem</em> is the root element.  <em>loader</em> is
an optional resource loader.  If omitted, it defaults to <a class="reference internal" href="#xml.etree.ElementTree.xml.etree.ElementInclude.default_loader" title="xml.etree.ElementTree.xml.etree.ElementInclude.default_loader"><code class="xref py py-func docutils literal notranslate"><span class="pre">default_loader()</span></code></a>.
If given, it should be a callable that implements the same interface as
<a class="reference internal" href="#xml.etree.ElementTree.xml.etree.ElementInclude.default_loader" title="xml.etree.ElementTree.xml.etree.ElementInclude.default_loader"><code class="xref py py-func docutils literal notranslate"><span class="pre">default_loader()</span></code></a>.  Returns the expanded resource.  If the parse mode is
<code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, this is an ElementTree instance.  If the parse mode is &quot;text&quot;,
this is a Unicode string.  If the loader fails, it can return None or
raise an exception.</p>
</dd></dl>

</div>
<div class="section" id="element-objects">
<span id="elementtree-element-objects"></span><h3>元素对象<a class="headerlink" href="#element-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.Element">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">Element</code><span class="sig-paren">(</span><em class="sig-param">tag</em>, <em class="sig-param">attrib={}</em>, <em class="sig-param">**extra</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element" title="永久链接至目标">¶</a></dt>
<dd><p>Element class.  This class defines the Element interface, and provides a
reference implementation of this interface.</p>
<p>The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings.  <em>tag</em> is the element name.  <em>attrib</em> is
an optional dictionary, containing element attributes.  <em>extra</em> contains
additional attributes, given as keyword arguments.</p>
<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.tag">
<code class="sig-name descname">tag</code><a class="headerlink" href="#xml.etree.ElementTree.Element.tag" title="永久链接至目标">¶</a></dt>
<dd><p>一个标识此元素意味着何种数据的字符串(换句话说，元素类型)。</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.text">
<code class="sig-name descname">text</code><a class="headerlink" href="#xml.etree.ElementTree.Element.text" title="永久链接至目标">¶</a></dt>
<dt id="xml.etree.ElementTree.Element.tail">
<code class="sig-name descname">tail</code><a class="headerlink" href="#xml.etree.ElementTree.Element.tail" title="永久链接至目标">¶</a></dt>
<dd><p>These attributes can be used to hold additional data associated with
the element.  Their values are usually strings but may be any
application-specific object.  If the element is created from
an XML file, the <em>text</em> attribute holds either the text between
the element's start tag and its first child or end tag, or <code class="docutils literal notranslate"><span class="pre">None</span></code>, and
the <em>tail</em> attribute holds either the text between the element's
end tag and the next tag, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  For the XML data</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="nt">&lt;a&gt;&lt;b&gt;</span>1<span class="nt">&lt;c&gt;</span>2<span class="nt">&lt;d/&gt;</span>3<span class="nt">&lt;/c&gt;&lt;/b&gt;</span>4<span class="nt">&lt;/a&gt;</span>
</pre></div>
</div>
<p>the <em>a</em> element has <code class="docutils literal notranslate"><span class="pre">None</span></code> for both <em>text</em> and <em>tail</em> attributes,
the <em>b</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">&quot;1&quot;</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">&quot;4&quot;</span></code>,
the <em>c</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">&quot;2&quot;</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">None</span></code>,
and the <em>d</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">None</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">&quot;3&quot;</span></code>.</p>
<p>To collect the inner text of an element, see <a class="reference internal" href="#xml.etree.ElementTree.Element.itertext" title="xml.etree.ElementTree.Element.itertext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itertext()</span></code></a>, for
example <code class="docutils literal notranslate"><span class="pre">&quot;&quot;.join(element.itertext())</span></code>.</p>
<p>Applications may store arbitrary objects in these attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.attrib">
<code class="sig-name descname">attrib</code><a class="headerlink" href="#xml.etree.ElementTree.Element.attrib" title="永久链接至目标">¶</a></dt>
<dd><p>A dictionary containing the element's attributes.  Note that while the
<em>attrib</em> value is always a real mutable Python dictionary, an ElementTree
implementation may choose to use another internal representation, and
create the dictionary only if someone asks for it.  To take advantage of
such implementations, use the dictionary methods below whenever possible.</p>
</dd></dl>

<p>The following dictionary-like methods work on the element attributes.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.Element.clear">
<code class="sig-name descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.clear" title="永久链接至目标">¶</a></dt>
<dd><p>Resets an element.  This function removes all subelements, clears all
attributes, and sets the text and tail attributes to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.get">
<code class="sig-name descname">get</code><span class="sig-paren">(</span><em class="sig-param">key</em>, <em class="sig-param">default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.get" title="永久链接至目标">¶</a></dt>
<dd><p>Gets the element attribute named <em>key</em>.</p>
<p>Returns the attribute value, or <em>default</em> if the attribute was not found.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.items">
<code class="sig-name descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.items" title="永久链接至目标">¶</a></dt>
<dd><p>Returns the element attributes as a sequence of (name, value) pairs.  The
attributes are returned in an arbitrary order.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.keys">
<code class="sig-name descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.keys" title="永久链接至目标">¶</a></dt>
<dd><p>Returns the elements attribute names as a list.  The names are returned
in an arbitrary order.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.set">
<code class="sig-name descname">set</code><span class="sig-paren">(</span><em class="sig-param">key</em>, <em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.set" title="永久链接至目标">¶</a></dt>
<dd><p>Set the attribute <em>key</em> on the element to <em>value</em>.</p>
</dd></dl>

<p>The following methods work on the element's children (subelements).</p>
<dl class="method">
<dt id="xml.etree.ElementTree.Element.append">
<code class="sig-name descname">append</code><span class="sig-paren">(</span><em class="sig-param">subelement</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.append" title="永久链接至目标">¶</a></dt>
<dd><p>Adds the element <em>subelement</em> to the end of this element's internal list
of subelements.  Raises <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if <em>subelement</em> is not an
<a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.extend">
<code class="sig-name descname">extend</code><span class="sig-paren">(</span><em class="sig-param">subelements</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.extend" title="永久链接至目标">¶</a></dt>
<dd><p>Appends <em>subelements</em> from a sequence object with zero or more elements.
Raises <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if a subelement is not an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.find">
<code class="sig-name descname">find</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.find" title="永久链接至目标">¶</a></dt>
<dd><p>Finds the first subelement matching <em>match</em>.  <em>match</em> may be a tag name
or a <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>.  Returns an element instance
or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <em>namespaces</em> is an optional mapping from namespace prefix
to full name.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.findall">
<code class="sig-name descname">findall</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.findall" title="永久链接至目标">¶</a></dt>
<dd><p>Finds all matching subelements, by tag name or
<a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>.  Returns a list containing all matching
elements in document order.  <em>namespaces</em> is an optional mapping from
namespace prefix to full name.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.findtext">
<code class="sig-name descname">findtext</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">default=None</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.findtext" title="永久链接至目标">¶</a></dt>
<dd><p>Finds text for the first subelement matching <em>match</em>.  <em>match</em> may be
a tag name or a <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>.  Returns the text content
of the first matching element, or <em>default</em> if no element was found.
Note that if the matching element has no text content an empty string
is returned. <em>namespaces</em> is an optional mapping from namespace prefix
to full name.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.getchildren">
<code class="sig-name descname">getchildren</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.getchildren" title="永久链接至目标">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified deprecated">3.2 版后已移除: </span>Use <code class="docutils literal notranslate"><span class="pre">list(elem)</span></code> or iteration.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.getiterator">
<code class="sig-name descname">getiterator</code><span class="sig-paren">(</span><em class="sig-param">tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.getiterator" title="永久链接至目标">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified deprecated">3.2 版后已移除: </span>Use method <a class="reference internal" href="#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.iter()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.insert">
<code class="sig-name descname">insert</code><span class="sig-paren">(</span><em class="sig-param">index</em>, <em class="sig-param">subelement</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.insert" title="永久链接至目标">¶</a></dt>
<dd><p>Inserts <em>subelement</em> at the given position in this element.  Raises
<a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if <em>subelement</em> is not an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.iter">
<code class="sig-name descname">iter</code><span class="sig-paren">(</span><em class="sig-param">tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.iter" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a tree <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> with the current element as the root.
The iterator iterates over this element and all elements below it, in
document (depth first) order.  If <em>tag</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> or <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, only
elements whose tag equals <em>tag</em> are returned from the iterator.  If the
tree structure is modified during iteration, the result is undefined.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.iterfind">
<code class="sig-name descname">iterfind</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.iterfind" title="永久链接至目标">¶</a></dt>
<dd><p>Finds all matching subelements, by tag name or
<a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>.  Returns an iterable yielding all
matching elements in document order. <em>namespaces</em> is an optional mapping
from namespace prefix to full name.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.itertext">
<code class="sig-name descname">itertext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.itertext" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a text iterator.  The iterator loops over this element and all
subelements, in document order, and returns all inner text.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.makeelement">
<code class="sig-name descname">makeelement</code><span class="sig-paren">(</span><em class="sig-param">tag</em>, <em class="sig-param">attrib</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.makeelement" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a new element object of the same type as this element.  Do not
call this method, use the <a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code class="xref py py-func docutils literal notranslate"><span class="pre">SubElement()</span></code></a> factory function instead.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.remove">
<code class="sig-name descname">remove</code><span class="sig-paren">(</span><em class="sig-param">subelement</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.remove" title="永久链接至目标">¶</a></dt>
<dd><p>Removes <em>subelement</em> from the element.  Unlike the find* methods this
method compares elements based on the instance identity, not on tag value
or contents.</p>
</dd></dl>

<p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> objects also support the following sequence type methods
for working with subelements: <a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>.</p>
<p>Caution: Elements with no subelements will test as <code class="docutils literal notranslate"><span class="pre">False</span></code>.  This behavior
will change in future versions.  Use specific <code class="docutils literal notranslate"><span class="pre">len(elem)</span></code> or <code class="docutils literal notranslate"><span class="pre">elem</span> <span class="pre">is</span>
<span class="pre">None</span></code> test instead.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">element</span> <span class="o">=</span> <span class="n">root</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="ow">not</span> <span class="n">element</span><span class="p">:</span>  <span class="c1"># careful!</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;element not found, or element has no subelements&quot;</span><span class="p">)</span>

<span class="k">if</span> <span class="n">element</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;element not found&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="elementtree-objects">
<span id="elementtree-elementtree-objects"></span><h3>ElementTree 对象<a class="headerlink" href="#elementtree-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.ElementTree">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">ElementTree</code><span class="sig-paren">(</span><em class="sig-param">element=None</em>, <em class="sig-param">file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree" title="永久链接至目标">¶</a></dt>
<dd><p>ElementTree wrapper class.  This class represents an entire element
hierarchy, and adds some extra support for serialization to and from
standard XML.</p>
<p><em>element</em> is the root element.  The tree is initialized with the contents
of the XML <em>file</em> if given.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree._setroot">
<code class="sig-name descname">_setroot</code><span class="sig-paren">(</span><em class="sig-param">element</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree._setroot" title="永久链接至目标">¶</a></dt>
<dd><p>Replaces the root element for this tree.  This discards the current
contents of the tree, and replaces it with the given element.  Use with
care.  <em>element</em> is an element instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.find">
<code class="sig-name descname">find</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.find" title="永久链接至目标">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.find()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.findall">
<code class="sig-name descname">findall</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.findall" title="永久链接至目标">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findall()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.findtext">
<code class="sig-name descname">findtext</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">default=None</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.findtext" title="永久链接至目标">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findtext" title="xml.etree.ElementTree.Element.findtext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findtext()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.getiterator">
<code class="sig-name descname">getiterator</code><span class="sig-paren">(</span><em class="sig-param">tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.getiterator" title="永久链接至目标">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified deprecated">3.2 版后已移除: </span>Use method <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.iter" title="xml.etree.ElementTree.ElementTree.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.iter()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.getroot">
<code class="sig-name descname">getroot</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.getroot" title="永久链接至目标">¶</a></dt>
<dd><p>Returns the root element for this tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.iter">
<code class="sig-name descname">iter</code><span class="sig-paren">(</span><em class="sig-param">tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.iter" title="永久链接至目标">¶</a></dt>
<dd><p>Creates and returns a tree iterator for the root element.  The iterator
loops over all elements in this tree, in section order.  <em>tag</em> is the tag
to look for (default is to return all elements).</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.iterfind">
<code class="sig-name descname">iterfind</code><span class="sig-paren">(</span><em class="sig-param">match</em>, <em class="sig-param">namespaces=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.iterfind" title="永久链接至目标">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.iterfind" title="xml.etree.ElementTree.Element.iterfind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.iterfind()</span></code></a>, starting at the root of the tree.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.parse">
<code class="sig-name descname">parse</code><span class="sig-paren">(</span><em class="sig-param">source</em>, <em class="sig-param">parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.parse" title="永久链接至目标">¶</a></dt>
<dd><p>Loads an external XML section into this element tree.  <em>source</em> is a file
name or <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>.  <em>parser</em> is an optional parser instance.
If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns the
section root element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.write">
<code class="sig-name descname">write</code><span class="sig-paren">(</span><em class="sig-param">file</em>, <em class="sig-param">encoding=&quot;us-ascii&quot;</em>, <em class="sig-param">xml_declaration=None</em>, <em class="sig-param">default_namespace=None</em>, <em class="sig-param">method=&quot;xml&quot;</em>, <em class="sig-param">*</em>, <em class="sig-param">short_empty_elements=True</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.write" title="永久链接至目标">¶</a></dt>
<dd><p>Writes the element tree to a file, as XML.  <em>file</em> is a file name, or a
<a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> opened for writing.  <em>encoding</em> <a class="footnote-reference brackets" href="#id8" id="id6">1</a> is the output
encoding (default is US-ASCII).
<em>xml_declaration</em> controls if an XML declaration should be added to the
file.  Use <code class="docutils literal notranslate"><span class="pre">False</span></code> for never, <code class="docutils literal notranslate"><span class="pre">True</span></code> for always, <code class="docutils literal notranslate"><span class="pre">None</span></code>
for only if not US-ASCII or UTF-8 or Unicode (default is <code class="docutils literal notranslate"><span class="pre">None</span></code>).
<em>default_namespace</em> sets the default XML namespace (for &quot;xmlns&quot;).
<em>method</em> is either <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is
<code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).
The keyword-only <em>short_empty_elements</em> parameter controls the formatting
of elements that contain no content.  If <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), they are
emitted as a single self-closed tag, otherwise they are emitted as a pair
of start/end tags.</p>
<p>The output is either a string (<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>) or binary (<a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>).
This is controlled by the <em>encoding</em> argument.  If <em>encoding</em> is
<code class="docutils literal notranslate"><span class="pre">&quot;unicode&quot;</span></code>, the output is a string; otherwise, it's binary.  Note that
this may conflict with the type of <em>file</em> if it's an open
<a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>; make sure you do not try to write a string to a
binary stream and vice versa.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能: </span><em>short_empty_elements</em> 形参。</p>
</div>
</dd></dl>

</dd></dl>

<p>This is the XML file that is going to be manipulated:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">html</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">head</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">title</span><span class="o">&gt;</span><span class="n">Example</span> <span class="n">page</span><span class="o">&lt;/</span><span class="n">title</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="n">head</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">body</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">p</span><span class="o">&gt;</span><span class="n">Moved</span> <span class="n">to</span> <span class="o">&lt;</span><span class="n">a</span> <span class="n">href</span><span class="o">=</span><span class="s2">&quot;http://example.org/&quot;</span><span class="o">&gt;</span><span class="n">example</span><span class="o">.</span><span class="n">org</span><span class="o">&lt;/</span><span class="n">a</span><span class="o">&gt;</span>
        <span class="ow">or</span> <span class="o">&lt;</span><span class="n">a</span> <span class="n">href</span><span class="o">=</span><span class="s2">&quot;http://example.com/&quot;</span><span class="o">&gt;</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">&lt;/</span><span class="n">a</span><span class="o">&gt;.&lt;/</span><span class="n">p</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="n">body</span><span class="o">&gt;</span>
<span class="o">&lt;/</span><span class="n">html</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>Example of changing the attribute &quot;target&quot; of every link in first paragraph:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">xml.etree.ElementTree</span> <span class="kn">import</span> <span class="n">ElementTree</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span> <span class="o">=</span> <span class="n">ElementTree</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;index.xhtml&quot;</span><span class="p">)</span>
<span class="go">&lt;Element &#39;html&#39; at 0xb77e6fac&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s2">&quot;body/p&quot;</span><span class="p">)</span>     <span class="c1"># Finds first occurrence of tag p in body</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
<span class="go">&lt;Element &#39;p&#39; at 0xb77ec26c&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">links</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">))</span>   <span class="c1"># Returns list of all links</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">links</span>
<span class="go">[&lt;Element &#39;a&#39; at 0xb77ec2ac&gt;, &lt;Element &#39;a&#39; at 0xb77ec1cc&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span>             <span class="c1"># Iterates through all found links</span>
<span class="gp">... </span>    <span class="n">i</span><span class="o">.</span><span class="n">attrib</span><span class="p">[</span><span class="s2">&quot;target&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;blank&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;output.xhtml&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="qname-objects">
<span id="elementtree-qname-objects"></span><h3>QName Objects<a class="headerlink" href="#qname-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.QName">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">QName</code><span class="sig-paren">(</span><em class="sig-param">text_or_uri</em>, <em class="sig-param">tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.QName" title="永久链接至目标">¶</a></dt>
<dd><p>QName wrapper.  This can be used to wrap a QName attribute value, in order
to get proper namespace handling on output.  <em>text_or_uri</em> is a string
containing the QName value, in the form {uri}local, or, if the tag argument
is given, the URI part of a QName.  If <em>tag</em> is given, the first argument is
interpreted as a URI, and this argument is interpreted as a local name.
<a class="reference internal" href="#xml.etree.ElementTree.QName" title="xml.etree.ElementTree.QName"><code class="xref py py-class docutils literal notranslate"><span class="pre">QName</span></code></a> instances are opaque.</p>
</dd></dl>

</div>
<div class="section" id="treebuilder-objects">
<span id="elementtree-treebuilder-objects"></span><h3>TreeBuilder Objects<a class="headerlink" href="#treebuilder-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.TreeBuilder">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">TreeBuilder</code><span class="sig-paren">(</span><em class="sig-param">element_factory=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder" title="永久链接至目标">¶</a></dt>
<dd><p>Generic element structure builder.  This builder converts a sequence of
start, data, and end method calls to a well-formed element structure.  You
can use this class to build an element structure using a custom XML parser,
or a parser for some other XML-like format.  <em>element_factory</em>, when given,
must be a callable accepting two positional arguments: a tag and
a dict of attributes.  It is expected to return a new element instance.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.close">
<code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.close" title="永久链接至目标">¶</a></dt>
<dd><p>Flushes the builder buffers, and returns the toplevel document
element.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.data">
<code class="sig-name descname">data</code><span class="sig-paren">(</span><em class="sig-param">data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.data" title="永久链接至目标">¶</a></dt>
<dd><p>Adds text to the current element.  <em>data</em> is a string.  This should be
either a bytestring, or a Unicode string.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.end">
<code class="sig-name descname">end</code><span class="sig-paren">(</span><em class="sig-param">tag</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.end" title="永久链接至目标">¶</a></dt>
<dd><p>Closes the current element.  <em>tag</em> is the element name.  Returns the
closed element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.start">
<code class="sig-name descname">start</code><span class="sig-paren">(</span><em class="sig-param">tag</em>, <em class="sig-param">attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.start" title="永久链接至目标">¶</a></dt>
<dd><p>Opens a new element.  <em>tag</em> is the element name.  <em>attrs</em> is a dictionary
containing element attributes.  Returns the opened element.</p>
</dd></dl>

<p>In addition, a custom <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> object can provide the
following method:</p>
<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.doctype">
<code class="sig-name descname">doctype</code><span class="sig-paren">(</span><em class="sig-param">name</em>, <em class="sig-param">pubid</em>, <em class="sig-param">system</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.doctype" title="永久链接至目标">¶</a></dt>
<dd><p>Handles a doctype declaration.  <em>name</em> is the doctype name.  <em>pubid</em> is
the public identifier.  <em>system</em> is the system identifier.  This method
does not exist on the default <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> class.</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="xmlparser-objects">
<span id="elementtree-xmlparser-objects"></span><h3>XMLParser对象<a class="headerlink" href="#xmlparser-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.XMLParser">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">XMLParser</code><span class="sig-paren">(</span><em class="sig-param">html=0</em>, <em class="sig-param">target=None</em>, <em class="sig-param">encoding=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser" title="永久链接至目标">¶</a></dt>
<dd><p>This class is the low-level building block of the module.  It uses
<a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> for efficient, event-based parsing of XML.  It can
be fed XML data incrementally with the <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.feed" title="xml.etree.ElementTree.XMLParser.feed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">feed()</span></code></a> method, and parsing
events are translated to a push API - by invoking callbacks on the <em>target</em>
object.  If <em>target</em> is omitted, the standard <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> is used.
The <em>html</em> argument was historically used for backwards compatibility and is
now deprecated.  If <em>encoding</em> <a class="footnote-reference brackets" href="#id8" id="id7">1</a> is given, the value overrides the
encoding specified in the XML file.</p>
<div class="deprecated">
<p><span class="versionmodified deprecated">3.4 版后已移除: </span>The <em>html</em> argument.  The remaining arguments should be passed via
keyword to prepare for the removal of the <em>html</em> argument.</p>
</div>
<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.close">
<code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.close" title="永久链接至目标">¶</a></dt>
<dd><p>Finishes feeding data to the parser.  Returns the result of calling the
<code class="docutils literal notranslate"><span class="pre">close()</span></code> method of the <em>target</em> passed during construction; by default,
this is the toplevel document element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.doctype">
<code class="sig-name descname">doctype</code><span class="sig-paren">(</span><em class="sig-param">name</em>, <em class="sig-param">pubid</em>, <em class="sig-param">system</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.doctype" title="永久链接至目标">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified deprecated">3.2 版后已移除: </span>Define the <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder.doctype" title="xml.etree.ElementTree.TreeBuilder.doctype"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TreeBuilder.doctype()</span></code></a> method on a custom TreeBuilder
target.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.feed">
<code class="sig-name descname">feed</code><span class="sig-paren">(</span><em class="sig-param">data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.feed" title="永久链接至目标">¶</a></dt>
<dd><p>Feeds data to the parser.  <em>data</em> is encoded data.</p>
</dd></dl>

<p><a class="reference internal" href="#xml.etree.ElementTree.XMLParser.feed" title="xml.etree.ElementTree.XMLParser.feed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLParser.feed()</span></code></a> calls <em>target</em>'s <code class="docutils literal notranslate"><span class="pre">start(tag,</span> <span class="pre">attrs_dict)</span></code> method
for each opening tag, its <code class="docutils literal notranslate"><span class="pre">end(tag)</span></code> method for each closing tag, and data
is processed by method <code class="docutils literal notranslate"><span class="pre">data(data)</span></code>.  <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.close" title="xml.etree.ElementTree.XMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLParser.close()</span></code></a> calls
<em>target</em>'s method <code class="docutils literal notranslate"><span class="pre">close()</span></code>. <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> can be used not only for
building a tree structure. This is an example of counting the maximum depth
of an XML file:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">xml.etree.ElementTree</span> <span class="kn">import</span> <span class="n">XMLParser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MaxDepth</span><span class="p">:</span>                     <span class="c1"># The target object of the parser</span>
<span class="gp">... </span>    <span class="n">maxDepth</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>    <span class="n">depth</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">,</span> <span class="n">attrib</span><span class="p">):</span>   <span class="c1"># Called for each opening tag.</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">&gt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span><span class="p">:</span>
<span class="gp">... </span>            <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">depth</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">end</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span>             <span class="c1"># Called for each closing tag.</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">-=</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">pass</span>            <span class="c1"># We do not need to do anything with data.</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>    <span class="c1"># Called when all data has been parsed.</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">target</span> <span class="o">=</span> <span class="n">MaxDepth</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">XMLParser</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">target</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">exampleXml</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">&lt;a&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;b&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;/b&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;b&gt;</span>
<span class="gp">... </span><span class="s2">    &lt;c&gt;</span>
<span class="gp">... </span><span class="s2">      &lt;d&gt;</span>
<span class="gp">... </span><span class="s2">      &lt;/d&gt;</span>
<span class="gp">... </span><span class="s2">    &lt;/c&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;/b&gt;</span>
<span class="gp">... </span><span class="s2">&lt;/a&gt;&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="n">exampleXml</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="go">4</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="xmlpullparser-objects">
<span id="elementtree-xmlpullparser-objects"></span><h3>XMLPullParser对象<a class="headerlink" href="#xmlpullparser-objects" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.XMLPullParser">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">XMLPullParser</code><span class="sig-paren">(</span><em class="sig-param">events=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLPullParser" title="永久链接至目标">¶</a></dt>
<dd><p>A pull parser suitable for non-blocking applications.  Its input-side API is
similar to that of <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a>, but instead of pushing calls to a
callback target, <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLPullParser</span></code></a> collects an internal list of parsing
events and lets the user read from it. <em>events</em> is a sequence of events to
report back.  The supported events are the strings <code class="docutils literal notranslate"><span class="pre">&quot;start&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;end&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;start-ns&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;end-ns&quot;</span></code> (the &quot;ns&quot; events are used to get detailed
namespace information).  If <em>events</em> is omitted, only <code class="docutils literal notranslate"><span class="pre">&quot;end&quot;</span></code> events are
reported.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.XMLPullParser.feed">
<code class="sig-name descname">feed</code><span class="sig-paren">(</span><em class="sig-param">data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLPullParser.feed" title="永久链接至目标">¶</a></dt>
<dd><p>Feed the given bytes data to the parser.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLPullParser.close">
<code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLPullParser.close" title="永久链接至目标">¶</a></dt>
<dd><p>Signal the parser that the data stream is terminated. Unlike
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser.close" title="xml.etree.ElementTree.XMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLParser.close()</span></code></a>, this method always returns <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.
Any events not yet retrieved when the parser is closed can still be
read with <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_events()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLPullParser.read_events">
<code class="sig-name descname">read_events</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="永久链接至目标">¶</a></dt>
<dd><p>Return an iterator over the events which have been encountered in the
data fed to the
parser.  The iterator yields <code class="docutils literal notranslate"><span class="pre">(event,</span> <span class="pre">elem)</span></code> pairs, where <em>event</em> is a
string representing the type of event (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;end&quot;</span></code>) and <em>elem</em> is the
encountered <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> object.</p>
<p>Events provided in a previous call to <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_events()</span></code></a> will not be
yielded again.  Events are consumed from the internal queue only when
they are retrieved from the iterator, so multiple readers iterating in
parallel over iterators obtained from <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read_events()</span></code></a> will have
unpredictable results.</p>
</dd></dl>

<div class="admonition note">
<p class="admonition-title">注解</p>
<p><a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLPullParser</span></code></a> only guarantees that it has seen the &quot;&gt;&quot;
character of a starting tag when it emits a &quot;start&quot; event, so the
attributes are defined, but the contents of the text and tail attributes
are undefined at that point.  The same applies to the element children;
they may or may not be present.</p>
<p>If you need a fully populated element, look for &quot;end&quot; events instead.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.4 新版功能.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="exceptions">
<h3>异常<a class="headerlink" href="#exceptions" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.ParseError">
<em class="property">class </em><code class="sig-prename descclassname">xml.etree.ElementTree.</code><code class="sig-name descname">ParseError</code><a class="headerlink" href="#xml.etree.ElementTree.ParseError" title="永久链接至目标">¶</a></dt>
<dd><p>XML parse error, raised by the various parsing methods in this module when
parsing fails.  The string representation of an instance of this exception
will contain a user-friendly error message.  In addition, it will have
the following attributes available:</p>
<dl class="attribute">
<dt id="xml.etree.ElementTree.ParseError.code">
<code class="sig-name descname">code</code><a class="headerlink" href="#xml.etree.ElementTree.ParseError.code" title="永久链接至目标">¶</a></dt>
<dd><p>A numeric error code from the expat parser. See the documentation of
<a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> for the list of error codes and their meanings.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.etree.ElementTree.ParseError.position">
<code class="sig-name descname">position</code><a class="headerlink" href="#xml.etree.ElementTree.ParseError.position" title="永久链接至目标">¶</a></dt>
<dd><p>A tuple of <em>line</em>, <em>column</em> numbers, specifying where the error occurred.</p>
</dd></dl>

</dd></dl>

<p class="rubric">备注</p>
<dl class="footnote brackets">
<dt class="label" id="id8"><span class="brackets">1</span><span class="fn-backref">(<a href="#id1">1</a>,<a href="#id2">2</a>,<a href="#id6">3</a>,<a href="#id7">4</a>)</span></dt>
<dd><p>The encoding string included in XML output should conform to the
appropriate standards.  For example, &quot;UTF-8&quot; is valid, but &quot;UTF8&quot; is
not.  See <a class="reference external" href="https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl">https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl</a>
and <a class="reference external" href="https://www.iana.org/assignments/character-sets/character-sets.xhtml">https://www.iana.org/assignments/character-sets/character-sets.xhtml</a>.</p>
</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> ---  ElementTree XML API</a><ul>
<li><a class="reference internal" href="#tutorial">教程</a><ul>
<li><a class="reference internal" href="#xml-tree-and-elements">XML树和元素</a></li>
<li><a class="reference internal" href="#parsing-xml">解析XML</a></li>
<li><a class="reference internal" href="#pull-api-for-non-blocking-parsing">Pull API进行非阻塞解析</a></li>
<li><a class="reference internal" href="#finding-interesting-elements">寻找有趣的元素</a></li>
<li><a class="reference internal" href="#modifying-an-xml-file">修改XML文件</a></li>
<li><a class="reference internal" href="#building-xml-documents">构建XML文档</a></li>
<li><a class="reference internal" href="#parsing-xml-with-namespaces">使用命名空间解析XML</a></li>
<li><a class="reference internal" href="#additional-resources">其他资源</a></li>
</ul>
</li>
<li><a class="reference internal" href="#xpath-support">XPath支持</a><ul>
<li><a class="reference internal" href="#example">示例</a></li>
<li><a class="reference internal" href="#supported-xpath-syntax">支持的XPath语法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reference">参考</a><ul>
<li><a class="reference internal" href="#functions">函数</a></li>
</ul>
</li>
<li><a class="reference internal" href="#xinclude-support">XInclude 支持</a><ul>
<li><a class="reference internal" href="#id3">示例</a></li>
</ul>
</li>
<li><a class="reference internal" href="#id4">参考</a><ul>
<li><a class="reference internal" href="#elementinclude-functions">函数</a></li>
<li><a class="reference internal" href="#element-objects">元素对象</a></li>
<li><a class="reference internal" href="#elementtree-objects">ElementTree 对象</a></li>
<li><a class="reference internal" href="#qname-objects">QName Objects</a></li>
<li><a class="reference internal" href="#treebuilder-objects">TreeBuilder Objects</a></li>
<li><a class="reference internal" href="#xmlparser-objects">XMLParser对象</a></li>
<li><a class="reference internal" href="#xmlpullparser-objects">XMLPullParser对象</a></li>
<li><a class="reference internal" href="#exceptions">异常</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="xml.html"
                        title="上一章">XML处理模块</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="xml.dom.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code> --- The Document Object Model API</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/xml.etree.elementtree.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="xml.dom --- The Document Object Model API"
             >下一页</a> |</li>
        <li class="right" >
          <a href="xml.html" title="XML处理模块"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >结构化标记处理工具</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>